<script setup>
import { ref, defineEmits,defineProps ,watch} from 'vue'
import { ElMessage} from 'element-plus'
/*import { UploadFilled } from '@element-plus/icons-vue'*/
import {put} from "@/http/http"

const props = defineProps({
  data: {
    type: Object,
    required: true
  }
})
watch(() => props.data, (newVal) => {
  formData.value = JSON.parse(JSON.stringify(newVal))
}, { deep: true })

const emit = defineEmits(["editeValue"])
const formRef = ref(null)

// 深拷贝数据避免直接修改props
const formData = ref(JSON.parse(JSON.stringify(props.data)))

// 咨询师列表（可从接口获取）
/*const consultants = ref([
  {id: 1, name: "张三"},
  {id: 2, name: "李四"},
  {id: 3, name: "王五"}
])*/

// 图片上传处理
/*const handleImageUpload = ({ file }) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.value.image = e.target.result // 暂存base64，实际应上传到服务器
  }
  reader.readAsDataURL(file)
}*/

// 时间格式处理
/*const format = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}*/

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  consultantId: [{ required: true, message: '请选择咨询师', trigger: 'change' }],
  consultationTime: [{ required: true, message: '请选择咨询时间', trigger: 'change' }]
}

// 提交处理
const handleSubmit = () => {

  let consultantId = JSON.parse(sessionStorage.getItem("consultant")).id;
  if (consultantId) {
    //向from中添加consultantId
    formData.value.consultantId = consultantId;
  }

  formRef.value.validate(valid => {
    if (valid) {
      // 发送PUT请求更新数据
      put(`/lzs/consultationRecord`, formData.value)
        .then(() => {
          ElMessage.success('保存成功')
          emit('editeValue', formData.value)
        })
        .catch(err => {
          console.error(err)
          ElMessage.error('保存失败，请稍后重试')
        })
    } else {
      ElMessage.error('请完善必填信息')
    }
  })
}
</script>

<template>
  <div class="edit-container">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-position="top"
    >
      <!-- 头部编辑区 -->
      <div class="edit-header">
        <!-- 图片上传 -->
<!--        <el-form-item label="封面图片" prop="image">
          <el-upload
              class="image-uploader"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleImageUpload"
          >
            <el-image
                v-if="formData.image"
                :src="formData.image"
                class="upload-image"
                fit="cover"
            />
            <el-icon v-else class="uploader-icon"><UploadFilled /></el-icon>
          </el-upload>
        </el-form-item>-->

        <!-- 基础信息 -->
        <div class="header-fields">
<!--          <el-form-item label="标题" prop="title">
            <el-input
                v-model="formData.title"
                placeholder="请输入咨询标题"
                clearable
            />
          </el-form-item>-->

<!--          <el-form-item label="咨询师" prop="consultantId">
            <el-select
                v-model="formData.consultantId"
                placeholder="请选择咨询师"
                filterable
            >
              <el-option
                  v-for="c in consultants"
                  :key="c.id"
                  :label="c.name"
                  :value="c.id"
              />
            </el-select>
          </el-form-item>-->

          <el-form-item label="咨询时间" prop="consultationTime">
            <el-date-picker
                v-model="formData.consultationTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择咨询时间"
            />
          </el-form-item>
        </div>
      </div>

      <!-- 详细信息双栏布局 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户信息">
            <el-input
                v-model="formData.userName"
                placeholder="输入用户姓名"
                clearable
                disabled
            />
          </el-form-item>

          <el-form-item label="诊断记录">
            <el-input
                v-model="formData.diagnosisRecord"
                type="textarea"
                :rows="4"
                placeholder="填写诊断记录"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="用户评价">
            <div v-if="formData.isReviewed=='0'" class="review-edit">
              <el-rate
                  v-model="formData.reviewRating"
                  :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              />
              <el-input
                  v-model="formData.reviewContent"
                  type="textarea"
                  :rows="3"
                  placeholder="填写评价内容"
                  class="review-input"
              />
              <el-date-picker
                  v-model="formData.reviewTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择评价时间"
                  class="review-time"
              />
            </div>
            <el-empty v-else description="尚未进行评价" />
          </el-form-item>

<!--          <el-form-item label="发布状态">
            <el-switch
                v-model="formData.isPublished"
                active-text="已发布"
                inactive-text="未发布"
            />
          </el-form-item>-->
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <div class="action-bar">
        <el-button @click="emit('cancel')">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存更改</el-button>
      </div>
    </el-form>
  </div>
</template>

<style scoped>
.edit-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0,0,0,0.05);
}

.edit-header {
  display: flex;
  gap: 24px;
  margin-bottom: 32px;
}

.image-uploader {
  width: 240px;
  height: 160px;
  border: 1px dashed var(--el-border-color);
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: border-color 0.3s;

  &:hover {
    border-color: var(--el-color-primary);
  }
}

.upload-image {
  width: 100%;
  height: 100%;
  border-radius: 6px;
}

.uploader-icon {
  font-size: 28px;
  color: var(--el-text-color-secondary);
}

.header-fields {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.review-edit {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .review-input {
    margin-top: 8px;
  }

  .review-time {
    align-self: flex-end;
  }
}

.action-bar {
  margin-top: 32px;
  text-align: right;
  padding-top: 24px;
  border-top: 1px solid var(--el-border-color-light);
}

/* 响应式处理 */
@media (max-width: 768px) {
  .edit-header {
    flex-direction: column;

    .image-uploader {
      width: 100%;
      height: 200px;
    }
  }

  .el-col {
    width: 100%;
    margin-bottom: 20px;
  }
}
</style>